﻿using GameServer.Managers;
using GameServer.Networking;
using GameServer.Networking.Packets;
using GameServer.Virtual_Objects.Room;
using GameServer.Virtual_Objects.User;
using System;
using System.Collections;
using System.Text;

namespace GameServer.Networking.Handlers
{
    internal class HANDLE_SPECTATE_ROOM : PacketHandler
    {
        public HANDLE_SPECTATE_ROOM()
        {
        }

        public override void Handle(virtualUser User)
        {
            bool flag;
            if (User.Rank <= 5)
            {
                User.disconnect();
            }
            else
            {
                int num = int.Parse(base.getNextBlock());
                int num1 = int.Parse(base.getNextBlock());
                if (num != 1)
                {
                    User.Room.removeSpectator(User);
                }
                else
                {
                    virtualRoom room = RoomManager.getRoom(User.Channel, num1);
                    if (room != null)
                    {
                        if (User.isSpectating)
                        {
                            return;
                        }
                        if (!room.addSpectator(User))
                        {
                            StringBuilder stringBuilder = new StringBuilder();
                            int num2 = 0;
                            foreach (virtualUser spectator in room.Spectators)
                            {
                                stringBuilder.Append(spectator.Nickname);
                                num2++;
                            }
                            stringBuilder.ToString().Remove(stringBuilder.ToString().Length - 1, 1);
                            User.send(new PACKET_CHAT("SPECTATE", PACKET_CHAT.ChatType.Room_ToAll, "SPECTATE >> There is no slot empty for this room!", (long)999, User.Nickname));
                        }
                        else
                        {
                            User.send(new PACKET_SPECTATE_ROOM(User, room));
                            User.send(new PACKET_ROOM_UDP(User, room.Players));
                            foreach (virtualUser player in room.Players)
                            {
                                flag = (player.Equals(User) ? true : player.isSpectating);
                                if (!flag)
                                {
                                    player.send(new PACKET_ROOM_UDP_SPECTATE(User));
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
